package login_service

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"

	app_global "app/app_src/framework/app/global"
	current_subject "app/app_src/framework/security/current/subject"
	security_util "app/app_src/framework/security/util"
	json_util "app/app_src/framework/util/json"
	context_path_util "app/app_src/framework/util/web/context_path"
	account_dao "app/app_src/modules/account/dao"
	login_constants "app/app_src/modules/login/constant"
)

// 检查认证信息
func CheckLogin(userName string, password string) (*current_subject.Subject, bool) {
	digestedPassword := security_util.Digest(password, app_global.SecretSalt())
	// 根据用户名获取用户信息
	userDalDTO := account_dao.GetUserDalDtoByUserName(userName)

	if (userDalDTO != nil) && (digestedPassword == userDalDTO.Password) {
		subject := current_subject.Subject{
			UserId:     userDalDTO.Id,
			UserType:   userDalDTO.UserType,
			UserName:   userDalDTO.UserName,
			Privileges: []string{},
			TenantId:   -1,
		}

		return &subject, true
	}

	return nil, false
}

// 保存登录信息
func SaveLoginSuccessInfo(ctx *gin.Context, subject *current_subject.Subject) {
	// 生成 CSRF 令牌
	cookiePath := context_path_util.WithContextPath("/")
	csrfToke := uuid.New().String()
	ctx.SetCookie(login_constants.CSRF_TOKEN_COOKIE_NAME, csrfToke, 0, cookiePath, "", false, false)

	// 记录用户信息到 session 中
	session := sessions.Default(ctx)
	session.Set(login_constants.SESSION_KEY_CURRENT_SUBJECT, json_util.ToString(*subject))
	session.Set(login_constants.SESSION_KEY_CSRF_TOKEN, csrfToke)
	session.Save()
}
